//初始化同步属性数据
function initPropertyList($propertyList, sourceFields, targetFields){
	var html = '';
	var sLen = sourceFields.length;
	var tLen = targetFields.length;
	if(sLen > 0 && sLen == tLen){
		//遍历初始化同步列表
		for (var i = 0; i < sLen; i++) {
			var sValue = sourceFields[i]['name'];
			var sType = sourceFields[i]['type'];
			var sTypeName = sourceFields[i]["typeName"];
			
			var tValue = targetFields[i]['name'];
			var tType = targetFields[i]['type'];
			var tTypeName = targetFields[i]["typeName"];
			var tr = '';
			tr += "<tr title='点击编辑' class='fastsyncer_pointer'>";
			tr += "<td type='"+sType+"' typeName='"+sTypeName+"'>"+sValue+"</td>";
			tr += "<td type='"+tType+"' typeName='"+tTypeName+"'>"+tValue+"</td>";
			tr += "<td><a class='fa fa-remove fa-2x propertyDelete fastsyncer_pointer' title='删除' ></a></td>";
			tr += "</tr>";
			html += tr;
		}
	}
	//将组装好的数据渲染给页面
	$propertyList.html(html);
	
	//删除同步属性按钮事件
	bindEventForDeleteProperty($(".propertyDelete"));
}

//添加同步属性按钮事件
function addProperty($propertyList, sourceField, targetField){
	var sValue = sourceField.attr("value");
	var sType = sourceField.attr("type");
	var sTypeName = sourceField.attr("typeName");
	var tValue = targetField.attr("value");
	var tType = targetField.attr("type");
	var tTypeName = targetField.attr("typeName");
	//校验唯一性
	if(!checkPropertyUnique($propertyList, sValue, tValue)){
		bootGrowl('已添加该属性.',"danger"); 
		return;
	}
	var html = '';
	html += "<tr title='点击编辑' class='fastsyncer_pointer'>";
	html += "<td type='"+ sType +"' typeName='"+sTypeName+"'>"+sValue+"</td>";
	html += "<td type='"+ tType +"' typeName='"+tTypeName+"'>"+tValue+"</td>";
	html += "<td><a class='fa fa-remove fa-2x propertyDelete fastsyncer_pointer' title='删除' ></a></td>";
	html += "</tr>";
	$propertyList.append(html);
}

//校验唯一性
function checkPropertyUnique($propertyList, sValue, tValue){
	var isOk = true;
	var trs = $propertyList.find("tr");
	trs.each(function(i,o){
		var sField = $(this).find("td:eq(0)").text();
		var tField = $(this).find("td:eq(1)").text();
		//如果有重复添加，返回false
		if(sValue==sField && tValue==tField ){
			isOk = false;
			//结束校验
			return false;
		}
	});
	return isOk;
}

//删除同步属性按钮事件
function bindEventForDeleteProperty($propertyDelete){
	//删除同步属性按钮事件
	$propertyDelete.click(function(){
		var tr = $(this).parent().parent();
		tr.remove();
	});
}

//初始化同步属性数据
function bindChangeEventForPropertyColumn($this, columns){
	var colLen = columns.length;
	var opts = "";
	for (var i = 0; i < colLen; i++) {
		var col = columns[i];
		var name = col['name'];
		var type = col['type'];
		var typeName = col['typeName'];
		opts += "<option value='"+ name +"' type='"+ type +"' typeName='"+ typeName +"' >"+ name +" ("+typeName+")</option>";
	}
	$this.html(opts);
}

$(function() {
	var sourceMapping = driver.sourceMapping;
	var targetMapping = driver.mappings[0];
	
	var $sourceCols = $("#propertySourceCols");
	var $targetCols = $("#propertyTargetCols");
	var $propertyList = $("#propertyList");
	var $propertyAdd = $("#propertyAdd");
	var $propertyDelete = $(".propertyDelete");
	
	//绑定数据源下拉切换事件
	$sourceCols.change(function(){
		$targetCols.find("option").removeAttr("selected");
		//选中的数据源字段
		var sourceVal = $(this).find(":selected").val();
		//自动选中目标源类似字段
		$targetCols.find("option").each(function(i,o){
			if(sourceVal==$(this).val()){
				$(this).attr("selected",true);
				return false;
			}
		});
	});
	//初始化同步属性数据
	//数据源
	bindChangeEventForPropertyColumn($sourceCols, sourceMapping.config.column);
	//目标源
	bindChangeEventForPropertyColumn($targetCols, targetMapping.config.column);
	//初始化已有属性列表
	initPropertyList($propertyList, sourceMapping.fileds, targetMapping.fileds);
	//为基本配置中表格的Tr绑定转换目标源同步属性按钮事件
	bindClickEventForPropertyListTr($propertyList.find("tr"));
	
	//同步属性按钮添加事件
	$propertyAdd.click(function(){
		var sourceField = $sourceCols.find(":selected");
		var targetField = $targetCols.find(":selected");
		addProperty($propertyList, sourceField, targetField);
		
		//重新绑定按钮删除事件
		bindEventForDeleteProperty($(".propertyDelete"));
		
		//为基本配置中表格的Tr绑定转换目标源同步属性按钮事件
		bindClickEventForPropertyListTr($("#propertyList").find("tr"));
	});
	
	// 初始化select2插件
	$(".select-control").select2({
		width : "100%",
		theme : "classic",
		// Infinity展示的Option个数不限制
		minimumResultsForSearch : Infinity
	});
	
});

//*********************************** Convertor转换器配置 *********************************//

//组装目标源转换属性字段
function assembleConvertFields(dialog) {
	// 获取目标源转换属性输入值
	var info = dialog.getModalContent();
	var $propertyConvertList = $(info).find("#propertyConvertList");
	var trs = $propertyConvertList.find("tr");
	// 获取驱动连接器配置
	var ctor = driver.mappings[0].convertor;
	driver.mappings[0].convertor = (undefined == ctor || ctor == null) ? {}
			: ctor;
	// 获取目标源属性名称
	var targetPropertyName = $(info).find('.targetProperty').text();

	// 判断是否配置转换操作
	var convertor = driver.mappings[0].convertor;
	if (trs.length > 0) {
		convertor[targetPropertyName] = {};
	}
	trs.each(function(i, o) {
		// 获取操作类型
		var opr = $(this).find("td:eq(0)").attr("value");
		// 获取参数
		var tds = $(this).find("td:eq(1) span");
		// 循环参数列表["", "",""]
		var arr = convertor[targetPropertyName][opr]= [];
		$.each(tds, function(i, v) {
			var paras = $(tds[i]).text();
			arr.push(paras);
		});
	});
}

//展示预览结果
/**
 * 生成预览文本
 * @param $propertyConvertList 操作列表
 * @param $propertyConverPreview 预览文本存放元素标签
 * @returns
 */
function createConvertPreviewCommond($propertyConvertList,$propertyConverPreview){
	// 清空预览文本
	$propertyConverPreview.empty();
	// 默认转换前和转换的文本示例 '张?三'
	var previewBeforeText = previewAfterText = DriverConvertPreviewText;
	// 遍历操作列表
	var trs = $propertyConvertList.find("tr");
	trs.each(function(i, o) {
		// 获取操作类型
		var operator = $(this).find("td:eq(0)").attr("value");
		// 获取参数
		var tds = $(this).find("td:eq(1) span");
		var arg = $(tds[0]).text();
		var para = $(tds[1]).text();

		// 目标源转换转换操作处理
		switch (operator) {
		case 'replace':
			previewAfterText = previewAfterText.replace(arg, para);
			break;
		case 'prepend':
			previewAfterText = arg + previewAfterText;
			break;
		case 'append':
			previewAfterText = previewAfterText + arg;
			break;
		default:
			break;
		}
	});

	// 生成预览效果
	var previewHtml = previewBeforeText + '<b>转换后</b>' + previewAfterText;
	$propertyConverPreview.append(previewHtml);

	// 判断如果操作列表为空，则清空预览文本
	if (trs.length == 0) {
		// 清空预览文本
		$propertyConverPreview.empty();
	}
}

/**
 * 删除同步属性转换预览条件
 * @param $propertyConvertDelete 删除元素
 * @param $propertyConvertList 转换操作列表
 * @param $propertyConverPreview 预览标签元素
 * @returns
 */
function bindEventForDeleteConvertProperty($propertyConvertDelete, $propertyConvertList, $propertyConverPreview) {
	$propertyConvertDelete.click(function() {
		// 删除tr
		$(this).parent().parent().remove();
		// 重新生成预览结果
		createConvertPreviewCommond($propertyConvertList, $propertyConverPreview);
	});
}

/**
 * 绑定添加转换按钮事件
 * @param $dialogHtml 对话框页面
 * @returns
 */
function bindEventForAddConvertCondition($dialogHtml){
	// 新增转换按钮
	var $propertyConvertAdd = $dialogHtml.find("#propertyConvertAdd");
	// 操作列表
	var $propertyConvertList = $dialogHtml.find("#propertyConvertList");
	// 下拉操作
	var $propertyConvertOperator = $dialogHtml.find("#propertyConvertOperator");
	// 预览
	var $propertyConverPreview = $dialogHtml.find('#propertyConverPreview');

	// 绑定添加转换按钮事件
	$propertyConvertAdd.click(function() {
		// 获取转换下拉
		var propertyConvertOperator = $propertyConvertOperator.find(":selected").text();
		var operatorValue = $propertyConvertOperator.find(":selected").val();

		// 参数区域
		var $propertyConvertParas = $dialogHtml.find('input[name="propertyConvertParas"]');

		// 对同步属性转换表单进行必填校验
		if ($dialogHtml.formValidate() == false) {
			return false;
		}
		
		//循环操作列表，如果有相同操作，则不能重复添加
		var flag = true;
		var trs = $propertyConvertList.find("tr");
		$.each(trs,function(i,v){
			var oper = $(this).find('td:eq(0)').attr("value");
			if(oper == operatorValue){
				bootGrowl("不能重复添加操作","danger");
				flag = false;
				return false;
			}
		});
		if(!flag)return;
			
		// 循环添加参数
		var propertyConvertParaValue = '';
		$.each($propertyConvertParas, function(i, v) {
			propertyConvertParaValue += '<span class="badge">'+ v.value + '</span> &nbsp;';
			// 清空参数
			$(v).val('');
		});
		var html = '';
		html += "<tr>";
		html += "<td value='" + operatorValue + "'>"+ propertyConvertOperator + "</td>";
		html += "<td>" + propertyConvertParaValue + "</td>";
		html += "<td><a class='fa fa-remove fa-2x propertyConvertDelete fastsyncer_pointer' title='删除' ></a></td>";
		html += "</tr>";
		$propertyConvertList.append(html);
		
		// 绑定同步属性转换删除事件
		bindEventForDeleteConvertProperty($dialogHtml.find(".propertyConvertDelete"), $propertyConvertList,$propertyConverPreview);

		// 展示预览结果
		createConvertPreviewCommond($propertyConvertList,$propertyConverPreview);
	});
}

//为基本配置中表格的Tr绑定转换目标源同步属性按钮事件
function bindClickEventForPropertyListTr($propertyTr) {
	$propertyTr.click(function() {
		//取数据源，目标源属性值
		var sourceProperty =  $(this).find('td:eq(0)').text();
		var targetProperty =  $(this).find('td:eq(1)').text();
	
		// 初始化对话框
		var $dialogHtml =$('<div class="row">'
			+'<!-- 数据源属性-->'
			+'<div class="col-md-5">'
			+'<h4 class="sourceProperty">'+sourceProperty+'</h4>'
			+'</div>'
			
			+'<!-- 中间图标 -->'
			+'<div class="col-md-2 text-center outer">'
			+'<span class="fa fa-angle-double-right fa-2x"></span>'
			+'</div>'
			
			+'<!-- 目标源属性-->'
			+'<div class="col-md-5 text-right">'
			+'<h4 class="targetProperty">'+targetProperty+'</h4>'
			+'</div>'
			+'</div>'
			
			+'<!-- 转换配置-->'
			+'<form class="form-horizontal" role="form">'
			+'<br />'
			+'<div class="row">'
			+'<div class="col-md-4">'
			+'<div class="form-group">'
			+'<label class="col-sm-3 control-label">操作</label>'
			+'<div class="col-sm-9">'
			+'<select name="operator" id="propertyConvertOperator" class="form-control select-control">'
			+'<option value="replace" argNum="2">替换</option>'
			+'<option value="prepend" argNum="1">追加前缀</option>'
			+'<option value="append" argNum="1">追加后缀</option>'
			+'</select>'
			+'</div>'
			+'</div>'
			+'</div>'
			+'<div id="propertyConvertInput"></div>'
			+'</div>'
			+'<div class="row">'
			+'<div class="col-md-4"></div>'
			+'<div class="col-md-6"></div>'
			+'<div class="col-md-2 text-right outer">'
			+'<button id="propertyConvertAdd" type="button" class="btn btn-primary">'
			+'<span class="fa fa-plus">添加</span>'
			+'</button>'
			+'</div>'
			+'</div>'
	
			+'<!-- 转换条件预览 -->'
			+'<div class="row">'
			+'<table class="table table-hover container">'
			+'<caption>'
			+'<label class="control-label">&nbsp;&nbsp;预览:&nbsp;</label>'
			+'<code id="propertyConverPreview"></code>'
			+'</caption>'
			+'<colgroup>'
			+'<col width="33%"></col>'
		    +'<col width="33%"></col>'
		    +'<col width="33%"></col>'
		    +'</colgroup>'
			+'<thead>'
			+'<tr>'
			+'<th>操作</th>'
			+'<th>参数</th>'
			+'<th>操作</th>'
			+'</tr>'
			+'</thead>'
			+'<tbody id="propertyConvertList"></tbody>'
			+'</table>'
			+'</div>'
			+'</form>');
	
		BootstrapDialog.show({
			title : '数据转换',
			type : BootstrapDialog.TYPE_INFO,
			size : BootstrapDialog.SIZE_WIDE,
			message : function(dialog) {
				return $dialogHtml;
			},
			buttons : [ {
				label : '确定',
				cssClass : 'btn-primary',
				action : function(dialog) {
					// 组装目标源转换属性字段
					assembleConvertFields(dialog);
					 dialog.close();
				}
			}, {
				label : '取消',
				action : function(dialog) {
					dialog.close();
				}
			} ]
		});

		// 初始化select2插件
		$dialogHtml.find(".select-control").select2({
			width : '100%',
			theme : "classic",
			minimumResultsForSearch : Infinity
		// 永远消除搜索框
		});

		// 初始化目标源同步属性参数框
		initPropertyConvertPara($dialogHtml);

		// 绑定添加转换按钮事件
		bindEventForAddConvertCondition($dialogHtml);
		
		// 获取转化器配置对象
		var $convertor = driver.mappings[0].convertor;
		if ($convertor) {
			// 初始化已有目标源同步属性列表
			initPropertyConvertList($dialogHtml, $dialogHtml.find("#propertyConvertList"), $convertor);
		}
	});

}
/**
 * 初始化目标源同步属性参数框
 * @param $dialogHtml 弹出框页面
 * @returns
 */
function initPropertyConvertPara($dialogHtml){
	//初始化一个参数框
	var parahtml = '<div class="col-md-4">'
			+'<div class="form-group">'
			+'<label class="col-sm-3 control-label">参数</label>'
			+'<div class="col-sm-9">'
			+'<input type="text" name="propertyConvertParas" class="form-control" asd-valid="require">'
			+'</div>'
			+'</div>'
			+'</div>';
	
	//默认设置参数框，根据设置的argNum参数框个数决定
	var $propertyConvertOperator = $dialogHtml.find("select[name='operator']");
	var $propertyConvertInput = $dialogHtml.find('#propertyConvertInput');
	var defalutArgNum = $propertyConvertOperator.find(':selected').attr('argNum');
	// 循环下拉框确定参数个数
	var defalutParahtml = '';
	$propertyConvertInput.empty();
	defalutArgNum = parseInt(defalutArgNum);
	for (var i = 0; i < defalutArgNum; i++) {
		defalutParahtml += parahtml;
	}
	$propertyConvertInput.append(defalutParahtml);
	
	//操作切换事件
	$propertyConvertOperator.change(function() {
		var operatorCount = $(this).find(':selected').attr('argNum');
		// 循环下拉框确定参数个数
		var html = '';
		$propertyConvertInput.empty();
		for (var i = 0; i < parseInt(operatorCount); i++) {
			html += parahtml;
		}
		$propertyConvertInput.append(html);
	});
}
/**
 * 初始化已有目标源同步属性列表
 * @param $dialogHtml 弹出框页面
 * @param $propertyConvertList 显示操作操作列表
 * @param $convertor 获取转化器配置对象
 * @returns
 */
function initPropertyConvertList($dialogHtml, $propertyConvertList, $convertor){
	// 获取预览Code标签元素
	var $propertyConverPreview = $dialogHtml.find('#propertyConverPreview');
	// 获取目标源属性名称
	var targetPropertyName = $dialogHtml.find('.targetProperty').text();
	
	// 获取转化器配置对象中目标源属性配置 ID/USERNAME
	var attr = $convertor[targetPropertyName];
	// 判断属性值是否存在
	if(!attr){
		return;
	}
	
	//遍历已有条件列表
	// 操作配置 例如:value = prepend/append/replace
	$.each(attr, function(value) {
		// "prepend": ["XXXXXX","XXXXXX"]
		var operator = attr[value];
		
		// 循环回显参数
		var arg = '';
		$.each(operator, function(i, value) {
			arg += '<span class="badge">'+operator[i]+ '</span> &nbsp;'
		});
		//添加转换条件
		var html = '';
		html += "<tr>";
		html += "<td value='"+value+"'>"+DriverConvertType[value]+"</td>";
		html += "<td>"+arg+"</td>";
		html += "<td><a class='fa fa-remove fa-2x propertyConvertDelete fastsyncer_pointer' title='删除' ></a></td>";
		html += "</tr>";
		$propertyConvertList.append(html);
	});

	// 获取删除同步属性转换删除事件
	var $propertyConvertDelete = $dialogHtml.find(".propertyConvertDelete");
	bindEventForDeleteConvertProperty($propertyConvertDelete, $propertyConvertList, $propertyConverPreview);
	
	//展示预览结果
	createConvertPreviewCommond($propertyConvertList, $propertyConverPreview);
	
}
